﻿using H2.NET.DBUtility;
using H2.NET.Web.Workflow.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;

namespace H2.NET.Web.Workflow.Services
{
    public class JobService
    {
        public JobService()
        {
            DbHelperSQL.connectionString = PubConstant.GetConnectionString("bpmDB");
        }

        public Jobs GetByName(string name)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 * from [Jobs] ");
            strSql.Append(" where name=@name");
            SqlParameter[] parameters = {
					new SqlParameter("@name",name)
			};

            var model = new Jobs();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                model.name = ds.Tables[0].Rows[0]["name"].ToString().Trim();
                model.fullname = ds.Tables[0].Rows[0]["fullname"].ToString().Trim();
                return model;
            }
            else
            {
                return null;
            }
        }

        public bool UpdateFullName(string name,string fullname)
        {
            var sql = "update Jobs set fullname = @fullname where name = @name";
            SqlParameter[] parameters = {
					new SqlParameter("@name",name),
                    new SqlParameter("@fullname",fullname)
			};

            return DbHelperSQL.ExecuteSql(sql, parameters) > 0;
        }

        public List<Jobs> FindByKey(string key)
        {
            var sql = "select name,fullname from Jobs where name like '%" + key + "%' or fullname like '%" + key + "%'";

            DataSet ds = DbHelperSQL.Query(sql);

            var list = new List<Jobs>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                var job = new Jobs();
                job.name = row["name"].ToString().ToString().Trim();
                job.fullname = row["fullname"].ToString().ToString().Trim();
                list.Add(job);
            }

            return list;
        }
    }
}